package com.example.victory.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.victory.config.ServiceError;
import com.example.victory.swagger.handler.AppStaffGroupApiDelegate;
import com.example.victory.swagger.model.*;
import com.cgws.fintech.sdk.api.inner.crmapi.model.ApiRequesFsdp;
import com.cgws.fintech.sdk.api.inner.crmapi.model.ApiRequesFsdpData;
import com.cgws.fintech.sdk.api.inner.crmapi.model.ApiResponseFsdp;
import com.cgws.fintech.sdk.api.inner.crmapi.model.ApiResponseFsdpData;
import com.cgws.fintech.sdk.api.inner.security.model.Account;
import com.cgws.fintech.sdk.api.inner.security.model.Session;
import com.cgws.fintech.sdk.api.inner.security.model.User;
import com.cgws.fintech.sdk.api.inner.security.model.UserSession;
import com.cgws.fintech.sdk.common.exception.GlobalException;
import com.cgws.fintech.sdk.common.utils.MoneyHelper;
import com.cgws.fintech.sdk.inner.utils.web.SessionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class AppStaffGroupService implements AppStaffGroupApiDelegate {

    @Autowired
    InnerCustomerStaffGroupService innerCustomerStaffGroupService;

    @Autowired
    SessionService sessionService;

    /**
     * 返回所在部门对应的CRM部门编码
     * @return
     */
    private String getCurrentOrgId() {
        UserSession userSession = sessionService.getCurrentUserSession(true);
        User user = userSession.getUser();
        return user.getOrginazationCode();
    }


    MoneyHelper.Asset getBigDecimalMoney(JSONObject o, String key) {
        return MoneyHelper.formatMoneyWithUnit(o.getBigDecimal(key));
    }

    @Override
    public ResponseEntity<ApiResponseGetGroupOfOrg> getGroupOfOrg(ApiRequestGetGroupOfOrg param) {
        ApiRequestGetGroupOfOrgData params = param.getData();

        String orgId = param.getData().getOrgId();
        if (orgId == null || orgId.equals("me")) {
            orgId = getCurrentOrgId();
            if (orgId == null || orgId.equals("")) {
                throw new GlobalException(ServiceError.PERMISSION_DENIED);
            } else {
                // 自动设置已经识别的orgId
                param.getData().setOrgId(orgId);
            }
        }

        ApiRequesFsdp apiRequesFsdp = new ApiRequesFsdp();
        JSONObject.toJSONString(params);
        apiRequesFsdp.setData(new ApiRequesFsdpData().params(JSONObject.toJSONString(params)));
        ApiResponseFsdp apiResponseFsdp = innerCustomerStaffGroupService.tdlb(apiRequesFsdp).getBody();
        ApiResponseFsdpData apiResponseFsdpData = apiResponseFsdp.getData();
        log.info("getGroupOfOrg --> {}", apiResponseFsdpData.getResult());
        ApiResponseGetGroupOfOrg respObject = new ApiResponseGetGroupOfOrg();
        ApiResponseGetGroupOfOrgData respObjectData = new ApiResponseGetGroupOfOrgData();
        JSONObject jsonObj = JSONObject.parseObject(apiResponseFsdpData.getResult());
        JSONArray jsonArray = jsonObj.containsKey("items") ? jsonObj.getJSONArray("items") : null;
        List<ApiResponseGetGroupOfOrgDataItem> items = new ArrayList<>();
        jsonArray.stream().forEach(o -> {
            ApiResponseGetGroupOfOrgDataItem item = new ApiResponseGetGroupOfOrgDataItem();
            JSONObject oo = (JSONObject) o;
            item.setOrgId(oo.getString("orgId"));
            item.setTdId(oo.getInteger("tdId"));
            item.setTdName(oo.getString("tdName"));
            item.setTotalOfPersons(oo.getInteger("totalOfPersons"));
            items.add(item);

        });
        respObjectData.setTotalOfPersons(jsonObj.containsKey("totalOfPersons") ? jsonObj.getInteger("totalOfPersons") : null);
        respObjectData.setItems(items);
        respObject.setData(respObjectData);
        return ResponseEntity.ok().body(respObject);
    }

    @Override
    public ResponseEntity<ApiResponseInfoOfOrgGroup> infoOfOrgGroup(ApiRequestInfoOfOrgGroup param) {
        ApiRequestInfoOfOrgGroupData params = param.getData();

        String orgId = param.getData().getOrgId();
        if (orgId == null || orgId.equals("me")) {
            orgId = getCurrentOrgId();
            if (orgId == null || orgId.equals("")) {
                throw new GlobalException(ServiceError.PERMISSION_DENIED);
            } else {
                // 自动设置已经识别的orgId
                param.getData().setOrgId(orgId);
            }
        }

        ApiRequesFsdp apiRequesFsdp = new ApiRequesFsdp();
        JSONObject.toJSONString(params);
        apiRequesFsdp.setData(new ApiRequesFsdpData().params(JSONObject.toJSONString(params)));
        ApiResponseFsdp apiResponseFsdp = innerCustomerStaffGroupService.tdzlsj(apiRequesFsdp).getBody();
        ApiResponseFsdpData apiResponseFsdpData = apiResponseFsdp.getData();
        log.info("infoOfOrgGroup --> {}", apiResponseFsdpData.getResult());
        JSONObject jsonObj = JSONObject.parseObject(apiResponseFsdpData.getResult());

        ApiResponseInfoOfOrgGroup respObject = new ApiResponseInfoOfOrgGroup();
        ApiResponseInfoOfOrgGroupData respObjectData = new ApiResponseInfoOfOrgGroupData();
        MoneyHelper.Asset v;

        respObjectData.setKhsKf(jsonObj.getString("khsKf"));


        respObjectData.setXkkhsKf(jsonObj.getString("xkkhsKf"));

        v = getBigDecimalMoney(jsonObj, "zcKf");
        if (v != null) {
            respObjectData.setZcKf(v.getValue());
            respObjectData.setZcKfUnit(v.getUnit());
        }


        v = getBigDecimalMoney(jsonObj, "xzzcKf");
        if (v != null) {
            respObjectData.setXzzcKf(v.getValue());
            respObjectData.setXzzcKfUnit(v.getUnit());
        }

        respObjectData.setKhsFw(jsonObj.getString("khsFw"));

        v = getBigDecimalMoney(jsonObj, "zcFw");
        if (v != null) {
            respObjectData.setZcFw(v.getValue());
            respObjectData.setZcFwUnit(v.getUnit());
        }

        v = getBigDecimalMoney(jsonObj, "jylBn");
        if (v != null) {
            respObjectData.setJylBn(v.getValue());
            respObjectData.setJylBnUnit(v.getUnit());
        }

        v = getBigDecimalMoney(jsonObj, "jylBy");
        if (v != null) {
            respObjectData.setJylBy(v.getValue());
            respObjectData.setJylByUnit(v.getUnit());
        }

        v = getBigDecimalMoney(jsonObj, "yjBy");
        if (v != null) {
            respObjectData.setYjBy(v.getValue());
            respObjectData.setYjByUnit(v.getUnit());
        }

        v = getBigDecimalMoney(jsonObj, "yjBn");
        if (v != null) {
            respObjectData.setYjBn(v.getValue());
            respObjectData.setYjBnUnit(v.getUnit());
        }

        respObject.setData(respObjectData);
        return ResponseEntity.ok().body(respObject);
    }

    @Override
    public ResponseEntity<ApiResponseGetMemberInGroup> getMemberInGroup(ApiRequestGetMemberInGroup param) {
        ApiRequestGetMemberInGroupData params = param.getData();

        String orgId = param.getData().getOrgId();
        if (orgId == null || orgId.equals("me")) {
            orgId = getCurrentOrgId();
            if (orgId == null || orgId.equals("")) {
                throw new GlobalException(ServiceError.PERMISSION_DENIED);
            } else {
                // 自动设置已经识别的orgId
                param.getData().setOrgId(orgId);
            }
        }

        ApiRequesFsdp apiRequesFsdp = new ApiRequesFsdp();
        JSONObject.toJSONString(params);
        apiRequesFsdp.setData(new ApiRequesFsdpData().params(JSONObject.toJSONString(params)));

        ApiResponseFsdp apiResponseFsdp = innerCustomerStaffGroupService.tdcylb(apiRequesFsdp).getBody();
        ApiResponseFsdpData apiResponseFsdpData = apiResponseFsdp.getData();
        log.info("getMemberInGroup --> {}", apiResponseFsdpData.getResult());

        JSONArray jsonArray = JSONArray.parseArray(apiResponseFsdpData.getResult());
        List<ApiResponseGetMemberInGroupDataItem> items = new ArrayList<>();
        jsonArray.stream().forEach(i -> {
            JSONObject jsonObj = (JSONObject) i;
            ApiResponseGetMemberInGroupDataItem item = new ApiResponseGetMemberInGroupDataItem();
            item.setRyId(jsonObj.getInteger("ryId"));
            item.setRylb(jsonObj.getString("rylb"));
            item.setRyxm(jsonObj.getString("ryxm"));
            MoneyHelper.Asset v;

            v = getBigDecimalMoney(jsonObj, "xzzcKf");
            if (v != null) {
                item.setXzzcKf(v.getValue());
                item.setXzzcKfUnit(v.getUnit());
            }

            item.setKhsKf(jsonObj.getString("khsKf"));

            item.setXkkhsKf(jsonObj.getString("xkkhsKf"));

            v = getBigDecimalMoney(jsonObj, "zcKf");
            if (v != null) {
                item.setZcKf(v.getValue());
                item.setZcKfUnit(v.getUnit());
            }

            items.add(item);
          }
        );

        ApiResponseGetMemberInGroup respObject = new ApiResponseGetMemberInGroup();
        ApiResponseGetMemberInGroupData respObjectData = new ApiResponseGetMemberInGroupData();

        respObjectData.setItems(JSONArray.parseArray(apiResponseFsdpData.getResult(), ApiResponseGetMemberInGroupDataItem.class));

        respObjectData.setItems(items);
        respObject.setData(respObjectData);
        return ResponseEntity.ok().body(respObject);
    }

    @Override
    public ResponseEntity<ApiResponseInfoOfMemberInGroup> infoOfMemberInGroup(ApiRequestInfoOfMemberInGroup param) {
        ApiRequestInfoOfMemberInGroupData params = param.getData();

        String orgId = param.getData().getOrgId();
        if (orgId == null || orgId.equals("me")) {
            orgId = getCurrentOrgId();
            if (orgId == null || orgId.equals("")) {
                throw new GlobalException(ServiceError.PERMISSION_DENIED);
            } else {
                // 自动设置已经识别的orgId
                param.getData().setOrgId(orgId);
            }
        }

        ApiRequesFsdp apiRequesFsdp = new ApiRequesFsdp();
        JSONObject.toJSONString(params);
        apiRequesFsdp.setData(new ApiRequesFsdpData().params(JSONObject.toJSONString(params)));

        ApiResponseFsdp apiResponseFsdp = innerCustomerStaffGroupService.tdcysj(apiRequesFsdp).getBody();
        ApiResponseFsdpData apiResponseFsdpData = apiResponseFsdp.getData();
        log.info("infoOfMemberInGroup --> {}", apiResponseFsdpData.getResult());
        ApiResponseInfoOfMemberInGroup respObject = new ApiResponseInfoOfMemberInGroup();
        ApiResponseInfoOfMemberInGroupData respObjectData = new ApiResponseInfoOfMemberInGroupData();
        JSONObject jsonObj = JSONObject.parseObject(apiResponseFsdpData.getResult());
        MoneyHelper.Asset v;
        respObjectData.setRyxm(jsonObj.getString("ryxm"));
        respObjectData.setRylb(jsonObj.getString("rylb"));
        respObjectData.setKhsKf(jsonObj.getString("khsKf"));
        respObjectData.setXkkhsKf(jsonObj.getString("xkkhsKf"));

        v = getBigDecimalMoney(jsonObj, "xzzcKf");
        if (v != null) {
            respObjectData.setXzzcKf(v.getValue());
            respObjectData.setXzzcKfUnit(v.getUnit());
        }

        respObjectData.setKhsFw(jsonObj.getString("khsFw"));

        v = getBigDecimalMoney(jsonObj, "zcFw");
        if (v != null) {
            respObjectData.setZcFw(v.getValue());
            respObjectData.setZcFwUnit(v.getUnit());
        }

        v = getBigDecimalMoney(jsonObj, "zcKf");
        if (v != null) {
            respObjectData.setZcKf(v.getValue());
            respObjectData.setZcKfUnit(v.getUnit());
        }

        v = getBigDecimalMoney(jsonObj, "jylBn");
        if (v != null) {
            respObjectData.setJylBn(v.getValue());
            respObjectData.setJylBnUnit(v.getUnit());
        }

        v = getBigDecimalMoney(jsonObj, "jylBy");
        if (v != null) {
            respObjectData.setJylBy(v.getValue());
            respObjectData.setJylByUnit(v.getUnit());
        }

        v = getBigDecimalMoney(jsonObj, "yjBy");
        if (v != null) {
            respObjectData.setYjBy(v.getValue());
            respObjectData.setYjByUnit(v.getUnit());
        }

        v = getBigDecimalMoney(jsonObj, "yjBn");
        if (v != null) {
            respObjectData.setYjBn(v.getValue());
            respObjectData.setYjBnUnit(v.getUnit());
        }

        respObject.setData(respObjectData);
        return ResponseEntity.ok().body(respObject);
    }
}
